<template>
  <div class="add-teacher-account">
    <!-- 面包屑导航 -->
    <el-breadcrumb class="breadcrumb" separator="/">
      <el-breadcrumb-item @click="goBack" class="clickable">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item @click="goBack" class="clickable">教师管理</el-breadcrumb-item>
      <el-breadcrumb-item class="active">添加教师账号</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 表单区域 -->
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="teacher-form"
      >
        <!-- 账号信息 -->
        <el-form-item label="账号：" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="手机号：" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            style="width: 300px"
          />
        </el-form-item>

        <!-- 密码信息 -->
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码(最多6位)"
            maxlength="6"
            show-password
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="确认密码：" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            maxlength="6"
            show-password
            style="width: 300px"
          />
        </el-form-item>

        <!-- 头像上传 -->
        <el-form-item label="头像：" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            action="#"
            :auto-upload="false"
            :on-change="handleAvatarChange"
          >
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 PNG、JPG 格式，文件大小不超过 2MB</div>
        </el-form-item>

        <!-- 简介 -->
        <el-form-item label="简介：" prop="introduction">
          <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入简介(最多150字)"
            maxlength="150"
            show-word-limit
            style="width: 400px"
          />
        </el-form-item>

        <!-- 年龄 -->
        <el-form-item label="年龄：" prop="age">
          <el-input-number
            v-model="formData.age"
            :min="18"
            :max="80"
            style="width: 200px"
          />
        </el-form-item>

        <!-- 科目 -->
        <el-form-item label="科目：" prop="subject">
          <el-select
            v-model="formData.subject"
            placeholder="请选择科目"
            style="width: 200px"
          >
            <el-option label="语文" value="语文" />
            <el-option label="数学" value="数学" />
            <el-option label="英语" value="英语" />
            <el-option label="物理" value="物理" />
            <el-option label="化学" value="化学" />
            <el-option label="生物" value="生物" />
            <el-option label="历史" value="历史" />
            <el-option label="地理" value="地理" />
            <el-option label="政治" value="政治" />
          </el-select>
        </el-form-item>

        <!-- 佣金比例 -->
        <el-form-item label="佣金比例：" prop="commissionRate">
          <el-input-number
            v-model="formData.commissionRate"
            :min="0"
            :max="100"
            :precision="1"
            style="width: 200px"
          />
          <span style="margin-left: 10px">%</span>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="button-group">
          <el-button type="primary" @click="submitForm" :loading="submitting">
            提交
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  avatar: '',
  introduction: '',
  age: null,
  subject: '',
  commissionRate: 10
})

// 头像预览
const avatarUrl = ref('')
const submitting = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 6, message: '密码长度在 1 到 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  introduction: [
    { required: true, message: '请输入简介', trigger: 'blur' },
    { max: 150, message: '简介不能超过150个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 18, max: 80, message: '年龄必须在18-80之间', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择科目', trigger: 'change' }
  ],
  commissionRate: [
    { required: true, message: '请输入佣金比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '佣金比例必须在0-100之间', trigger: 'blur' }
  ]
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response, file) => {
  avatarUrl.value = URL.createObjectURL(file.raw)
  formData.avatar = response.url
}

// 头像文件改变
const handleAvatarChange = (file) => {
  if (file.raw) {
    avatarUrl.value = URL.createObjectURL(file.raw)
    formData.avatar = file.name
  }
}

// 返回上一页
const goBack = () => {
  router.push('/teacher-management')
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 模拟API调用
    setTimeout(() => {
      submitting.value = false
      ElMessage.success('教师账号添加成功！')
      
      // 添加成功后返回教师管理页面
      router.push('/teacher-management')
    }, 1500)

  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消添加教师账号吗？未保存的数据将丢失。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning',
    }
  ).then(() => {
    router.push('/teacher-management')
  }).catch(() => {
    // 用户选择继续编辑，不做任何操作
  })
}
</script>

<style scoped>
.add-teacher-account {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.breadcrumb .active {
  color: #409eff;
  font-weight: 600;
}

.breadcrumb .clickable {
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.breadcrumb .clickable:hover {
  color: #409eff;
}

.form-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.teacher-form {
  max-width: 600px;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.button-group {
  margin-top: 30px;
  text-align: center;
}

.button-group .el-button {
  margin: 0 10px;
  padding: 12px 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-teacher-account {
    padding: 10px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .teacher-form {
    max-width: 100%;
  }
  
  .teacher-form .el-input,
  .teacher-form .el-select,
  .teacher-form .el-input-number,
  .teacher-form .el-textarea {
    width: 100% !important;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

:deep(.el-upload:hover) {
  border-color: #409eff;
}
</style>